package com.hmall.gateway.filters;

import cn.hutool.core.util.StrUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author lxr
 * @version 1.0
 * @since 2025-09-06 10:37
 */
@Component
@EnableConfigurationProperties(AuthProperties.class)
@RequiredArgsConstructor
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final JwtTool jwtTool;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取到request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 2.获取请求路径
        String path = request.getPath().toString();
        // 3.获取要放行url规则列表
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String pattern : excludePaths) {
            boolean match = antPathMatcher.match(pattern, path);
            if(match) {
                //匹配路径成功，放行
                return chain.filter(exchange);
            }
        }
        String token = request.getHeaders().getFirst("authorization");
        boolean result = true;
        if(StrUtil.isBlank(token)) {
            log.error("Token不存在");
            result = false;
        } else {
            try {
                Long userId = jwtTool.parseToken(token);
                log.warn("网关中解析Token得到的用户信息:{}", userId);
                // 将userId放入请求头
                request.mutate().header("user-info", userId.toString());
            } catch (Exception e){
                result = false;
                log.error("Token非法");
            }
        }
        if(result) {
            return chain.filter(exchange);
        }
        // 校验失败
        // 设置状态码为401并结束响应
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
